package net.cardgame.orcalecard;

import java.lang.reflect.Type;
import java.util.ArrayList;

import jp.jma.oraclecard.R;
import net.cardgame.oraclecard.animation.FlakeView;
import net.cardgame.orcalecard.asynctask.DownloadListener;
import net.cardgame.orcalecard.asynctask.GetListDeckTask;
import net.cardgame.orcalecard.bean.DeckBean;
import net.cardgame.orcalecard.pref.SecurePreferences;
import net.cardgame.orcalecard.utils.ConstantValue;
import net.cardgame.orcalecard.utils.NetworkUtils;
import net.cardgame.orcalecard.utils.XmlParser;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

/**
 * Màn hình Home
 * 
 */
public class MainActivity extends Activity implements OnClickListener,
		DownloadListener {
	String config = "";
	ProgressDialog dialog;
	boolean gotoTopPage = false;
	boolean load_toppage_finished = false;
	FlakeView flakeView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		LinearLayout container = (LinearLayout) findViewById(R.id.container);
		flakeView = new FlakeView(this);
		container.addView(flakeView);
		getWindow().setBackgroundDrawable(new ColorDrawable(Color.BLACK));
		findViewById(R.id.btnMyPage).setOnClickListener(this);
		findViewById(R.id.btnInformation).setOnClickListener(this);
		getStatus();
	}

	/**
	 * 
	 */
	void getStatus() {
		SecurePreferences appPreferences = new SecurePreferences(this,
				ConstantValue.APP_PREFERENCES,
				ConstantValue.PREFERENCES_SECRET_KEY, true);
		if (appPreferences.containsKey(ConstantValue.KEY_LOAD_FINISHED_TOPPAGE)) {
			load_toppage_finished = true;
		}
		if (appPreferences.containsKey(ConstantValue.CONFIG_DECKBEAN_KEY)) {
			config = appPreferences
					.getString(ConstantValue.CONFIG_DECKBEAN_KEY);
		} else {
			if (NetworkUtils.isNetworkConnected(this)) {
				dialog = ProgressDialog.show(this, "", "Loading..Wait..", true);
				dialog.show();
				GetListDeckTask task = new GetListDeckTask(this);
				task.setDownloadListener(this);
				task.execute("");
			}
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
		SecurePreferences appPreferences = new SecurePreferences(this,
				ConstantValue.APP_PREFERENCES,
				ConstantValue.PREFERENCES_SECRET_KEY, true);
		if (appPreferences.containsKey(ConstantValue.KEY_LOAD_FINISHED_TOPPAGE)) {
			load_toppage_finished = true;
		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.btnMyPage: // go to my page activity
			if (config != null && config != "") {
				gotoToppage();
			} else {
				if (NetworkUtils.isNetworkConnected(this)) {
					gotoTopPage = true;
					dialog = ProgressDialog.show(this, "", "Loading..Wait..",
							true);
					dialog.show();
					GetListDeckTask task = new GetListDeckTask(this);
					task.setDownloadListener(this);
					task.execute("");
				} else
					showDialogSetting();
			}
			break;
		case R.id.btnInformation:// go to app information activity
			if (NetworkUtils.isNetworkConnected(this)) {
				Intent intent = new Intent(this, InfoAppActivity.class);
				startActivityForResult(intent, 1);
			} else
				showDialogSetting();
			break;
		default:
			break;
		}
	}

	void gotoToppage() {
		if (!load_toppage_finished && !NetworkUtils.isNetworkConnected(this)) {
			showDialogSetting();
			return;
		}
		Intent intent = new Intent(this, TopPageActivity.class);
		intent.putExtra("continue_download", 1);
		startActivityForResult(intent, 0);
		overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
		this.finish();
	}

	@Override
	public void onDownloadSuccessListener(String result) {
		// TODO Auto-generated method stub
		new saveXMLtoJson().execute(result);
	}

	@Override
	public void onDownloadFailListener(String result) {
		// TODO Auto-generated method stub
		if (dialog != null && dialog.isShowing()) {
			dialog.dismiss();
		}
	}

	@Override
	public void onProgressUpdateListener(Integer update) {
		// TODO Auto-generated method stub

	}

	void showDialogSetting() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		// Creates textview for centre title
		TextView myMsg = new TextView(this);
		String title = getResources().getString(
				R.string.dialog_errornetwork_title);
		String message = getResources().getString(
				R.string.dialog_errornetwork_message);
		myMsg.setText(title);
		myMsg.setGravity(Gravity.CENTER_HORIZONTAL);
		myMsg.setTextSize(20);
		myMsg.setTextColor(Color.WHITE);
		// set custom title
		builder.setCustomTitle(myMsg);
		builder.setMessage(message);
		builder.setNegativeButton("OK", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
				dialog.dismiss();
			}
		});
		builder.setPositiveButton("Setting",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						dialog.dismiss();
						startActivity(new Intent(
								android.provider.Settings.ACTION_SETTINGS));
					}
				});
		AlertDialog dialog = builder.show();
	}

	class saveXMLtoJson extends AsyncTask<String, Void, ArrayList<DeckBean>> {

		@Override
		protected ArrayList<DeckBean> doInBackground(String... params) {
			// TODO Auto-generated method stub
			return new XmlParser().getDeckBeans(params[0]);
		}

		@Override
		protected void onPostExecute(ArrayList<DeckBean> result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			SecurePreferences appPreferences = new SecurePreferences(
					MainActivity.this, ConstantValue.APP_PREFERENCES,
					ConstantValue.PREFERENCES_SECRET_KEY, true);
			Gson gson = new Gson();
			Type listOfDeckBean = new TypeToken<ArrayList<DeckBean>>() {
			}.getType();
			String save = gson.toJson(result, listOfDeckBean);
			appPreferences.put(ConstantValue.CONFIG_DECKBEAN_KEY, save);
			config = save;
			if (dialog != null && dialog.isShowing()) {
				dialog.dismiss();
			}
			if (gotoTopPage) {
				gotoToppage();
			}
		}

	}

	@Override
	protected void onPause() {
		super.onPause();
		if (flakeView != null)
			flakeView.pause();
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (flakeView != null)
			flakeView.resume();
	}
}
